import json
import os
from interface.frame.apis.base_api import BaseApi
from interface.frame.utils.log_utils import logger
from interface.frame.utils.utils import Utils


class AdminApi(BaseApi):

    def __init__(self):
        path = Utils.get_frame_root_path() + "/config/data.yaml"
        data = Utils.get_yaml_data(path)

        # 命令行输入，set user=manage  或者 set user=admin
        user = "admin"
        if os.getenv("user"):
            user = os.getenv("user")
        username = data.get('login').get(user).get("username")
        password = data.get('login').get(user).get("password")

        # 命令行输入 set env=DEV   或者 set env=TEST
        self.BASE_URL = "https://litemall.hogwarts.ceshiren.com/"
        if os.getenv("env"):
            _env = os.getenv("env")
            self.BASE_URL = data.get('BASE_URL').get(_env)
        self.token = self.get_token(username, password)

    def get_token(self, username, password):
        # 定义登录接口的URL
        login_url = "admin/auth/login"
        # 定义登录接口的请求包
        login_data = {"username": username, "password": password}
        # 组包请求体
        req = {
            "method": "post",
            "url": self.BASE_URL + login_url,
            "json": login_data
        }
        # 发起登录请求
        login_r = self.do_send(req)
        # 从响应结果中获取token
        token = login_r.json()["data"]["token"]
        return token

    def send_api(self, req):
        """
        重新封装do_send方法
        :param req:
        :return:
        """
        url = req['url']
        req['url'] = self.BASE_URL + url

        if req.get('headers'):
            req['headers']['X-Litemall-Admin-Token'] = self.token
        else:
            req['headers'] = {"X-Litemall-Admin-Token": self.token}

        r = self.do_send(req)
        logger.info(f"【{url}】的响应数据为：{json.dumps(r.json(), indent=2, ensure_ascii=False)}")
        return r
